package com.wing.order.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.order.model.entity.CabInventoryProduct;
import com.wing.order.model.request.CabInventoryProductForm;
import com.wing.order.model.response.CabInventoryProductVO;
import com.wing.order.service.CabInventoryProductService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-产品库存管理", tags = "#/order/cabInventoryProduct")
@RestController("cabInventoryProductController")
@RequestMapping("order/admin/cabInventoryProduct")
@RequiredArgsConstructor
@Slf4j
public class CabInventoryProductController {

    private final CabInventoryProductService cabInventoryProductService;


    @ApiOperation(value = "查询所有产品库存", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CabInventoryProduct> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
    ){

        Page<CabInventoryProduct> pg = new Page<>(page, limit);
        QueryWrapper<CabInventoryProduct> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索

        IPage<CabInventoryProduct> list = cabInventoryProductService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加产品库存", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CabInventoryProductForm.Add.class) @RequestBody CabInventoryProductForm cabInventoryProductForm) {
        try {

            QueryWrapper<CabInventoryProduct> queryWrapper = new QueryWrapper<CabInventoryProduct>();
            queryWrapper.eq("sku_code", cabInventoryProductForm.getSkuCode());
            queryWrapper.eq("warehouse_id", cabInventoryProductForm.getWarehouseId());
            queryWrapper.eq("source_type", cabInventoryProductForm.getSourceType());
            CabInventoryProduct cabInventoryProduct = cabInventoryProductService.getBaseMapper().selectOne(queryWrapper);
            if (null == cabInventoryProduct) {
                cabInventoryProductService.add(cabInventoryProductForm);
            }
            return JsonResult.success("添加成功");
        }catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail("添加失败:"+ e.getMessage());
        }
    }




    @ApiOperation(value = "修改产品库存", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CabInventoryProductForm.Update.class) @RequestBody CabInventoryProductForm cabInventoryProductForm) {

        CabInventoryProduct cabInventoryProduct = cabInventoryProductService.getById(cabInventoryProductForm.getId());
        if(cabInventoryProduct == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CabInventoryProduct.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cabInventoryProductForm, cabInventoryProduct, copyOptions);
        if (cabInventoryProductService.updateById(cabInventoryProduct)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除产品库存", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cabInventoryProductId", value = "产品库存id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/delete/{id}" )
    public JsonResult delete(@PathVariable("id") Long cabInventoryProductId) {

        if (cabInventoryProductService.removeById(cabInventoryProductId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 根据skuCode查询库存
     * @param skuCode
     * @return
     */
    @GetMapping("/getInventoryProduct")
    public JsonResult<CabInventoryProduct> getInventoryProductVOBySkuCode(String skuCode){

        CabInventoryProduct cabInventoryProduct = cabInventoryProductService.getInventoryProductVOBySkuCode(skuCode,null,null);
        return JsonResult.success(cabInventoryProduct);
    }
    /**
     * 根据skuCode查询库存
     * @param skuCode
     * @param skuCode
     * @return
     */
    @GetMapping("/getInventoryProduct2")
    public JsonResult<CabInventoryProduct> getInventoryProductVOBySkuCode(String skuCode,Long warehouseId,Integer sourceType){

        CabInventoryProduct cabInventoryProduct = cabInventoryProductService.getInventoryProductVOBySkuCode(skuCode,warehouseId,sourceType);
        return JsonResult.success(cabInventoryProduct);
    }

    @ApiOperation(value = "修改产品库存", notes = "修改")
    @PutMapping("/updateCabInventoryProduct")
    public JsonResult updateCabInventoryProduct(@RequestBody CabInventoryProduct cabInventoryProduct) {

        if(cabInventoryProduct == null){
            return JsonResult.fail("修改失败！");
        }
        if (cabInventoryProductService.updateById(cabInventoryProduct)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    /**
     * 根据skuCode和sourceType查询库存
     * @param skuCode
     * @return
     */
    @GetMapping("/getRepertoryBySkuCode")
    public JsonResult<List<CabInventoryProductVO>> getCabInventoryProductBySkuCodeAndType(@RequestParam("skuCode") String skuCode){
        return JsonResult.success(cabInventoryProductService.getCabInventoryProductBySkuCodeAndType(skuCode));
    }

    @ApiOperation(value = "删除产品库存根据SKU编码", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuCode", value = "SKU编码", required = true, dataType = "String", paramType = "query")
    })
    @DeleteMapping("/inventoryDeleteBySkuId" )
    public JsonResult inventoryDeleteBySkuId(@RequestParam("skuId") Long skuId) {
        try {

            QueryWrapper<CabInventoryProduct> queryWrapper = new QueryWrapper<CabInventoryProduct>();
            queryWrapper.eq("sku_id", skuId);
            cabInventoryProductService.remove(queryWrapper);
            return JsonResult.success("删除成功");
        }catch (Exception e){
            return JsonResult.fail("删除失败");
        }
    }


    @ApiOperation(value = "添加产品库存(简版)", notes = "添加")
    @PostMapping("/addCabInventoryProduct")
    public JsonResult addCabInventoryProduct(@Validated(CabInventoryProductForm.Add.class) @RequestBody CabInventoryProductForm cabInventoryProductForm) {
        try {
            cabInventoryProductService.saveCabInventoryProduct(cabInventoryProductForm);
            String msg = "入库成功";
            if(cabInventoryProductForm.getInOutType().equals("out")){
                msg = "出库成功";
            }
            return JsonResult.success(msg);
        }catch (Exception e) {
            log.error("入库失败:", e);
            return JsonResult.fail("提交失败:"+ e.getMessage());
        }
    }

}
